import mongoose from 'mongoose';
import { IUser } from '../models/user';
import { IPermission } from '../models/permission';

/**
 * 用户权限数据访问对象
 * 处理用户权限相关的数据库操作
 */
export class UserPermissionDAO {
  /**
   * 获取用户权限信息
   * @param userId 用户ID
   * @returns 用户权限信息
   */
  async getUserPermissions(userId: mongoose.Types.ObjectId): Promise<any> {
    try {
      // 通过用户角色获取权限
      const userRoles = await mongoose.connection.db?.collection('user_roles')
        .find({ userId })
        .toArray();
      
      if (!userRoles || userRoles.length === 0) {
        return { permissions: [], roles: [] };
      }
      
      const roleIds = userRoles.map(ur => ur.roleId);
      
      // 获取角色权限
      const rolePermissions = await mongoose.connection.db?.collection('role_permissions')
        .find({ roleId: { $in: roleIds } })
        .toArray();
      
      const permissionIds = rolePermissions?.map(rp => rp.permissionId) || [];
      
      // 获取权限详情
      const permissions = await mongoose.connection.db?.collection('permissions')
        .find({ _id: { $in: permissionIds } })
        .toArray();
      
      return {
        permissions: permissions || [],
        roles: roleIds
      };
    } catch (error) {
      throw new Error(`获取用户权限失败: ${error}`);
    }
  }
  
  /**
   * 批量获取用户权限
   * @param userIds 用户ID数组
   * @returns 用户权限映射
   */
  async batchGetUserPermissions(userIds: mongoose.Types.ObjectId[]): Promise<Record<string, any>> {
    try {
      const result: Record<string, any> = {};
      
      for (const userId of userIds) {
        result[userId.toString()] = await this.getUserPermissions(userId);
      }
      
      return result;
    } catch (error) {
      throw new Error(`批量获取用户权限失败: ${error}`);
    }
  }
  
  /**
   * 检查用户是否有特定权限
   * @param userId 用户ID
   * @param permissionCode 权限代码
   * @returns 是否有权限
   */
  async hasPermission(userId: mongoose.Types.ObjectId, permissionCode: string): Promise<boolean> {
    try {
      const userPermissions = await this.getUserPermissions(userId);
      return userPermissions.permissions.some((p: any) => p.code === permissionCode);
    } catch (error) {
      throw new Error(`检查用户权限失败: ${error}`);
    }
  }
}

export default UserPermissionDAO;